
<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" style="margin: 10px 0px" @click="showDialog">添加</el-button>
    <el-table style="width: 100%" border :data="list">
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column prop="logoUrl" label="品牌logo" width="width">
        <template slot-scope="{row}">
          <img :src="row.logoUrl" style="width:80px;height:80px;">
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{row, $index}">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="margin-top:20px;text-align:center;" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page="page" :total="total" :page-size="limit" :pager-count="7"
      :page-sizes="[3, 5, 10]" layout="prev, pager, next, jumper, ->, sizes, total">
    </el-pagination>

    <el-dialog :title="tmform.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <el-form style="width: 80%;" :model="tmform" :rules="rules" ref="tmform">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmform.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload class="avatar-uploader" :action="`${baseURL}/admin/product/fileUpload`" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="tmform.logoUrl" :src="tmform.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg文件，且不超过2Mb</div>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark('tmform')">确 定</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
export default {
  name: 'TradeMark',
  data() {
    var validateTmName = (rule, value, callback)=>{
      if(value.length < 2 || value.length > 10 ) {
        callback(new Error('品牌名称长度2-10位'));
      }else{
        callback()
      }

    }
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      page: 1, // 当前页码
      limit: 3, // 每页显示条数
      total: 0, // 总共数据条数
      list: [], // 列表展示的数据
      dialogFormVisible: false,
      imageUrl: '',
      // 收集品牌信息
      tmform: {
        tmName: '',
        logoUrl: ''
      },
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { validator: validateTmName, trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请上传品牌图片' }
        ]
      }
      
    }
  },
  mounted() {
    this.getPageList()
  },
  methods: {
    handleSizeChange(val) {
      this.limit = val
      this.getPageList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getPageList()
    },
    async getPageList() {
      const { page, limit } = this
      // 调用获取品牌列表的数据
      const result = await this.$API.trademark.reqTradeMarkList(page, limit)
      if (result.code === 200) {
        this.total = result.data.total
        this.list = result.data.records
      }
    },

    // 点击添加品牌的按钮
    showDialog() {
      this.dialogFormVisible = true
      // 清空tmform
      this.tmform = {tmName:'', logoUrl:''}
    },

    // 点击修改品牌的按钮
    updateTradeMark(row) {
      this.dialogFormVisible = true
      // 重置tmform
      // this.tmform = {id:row.id, tmName:row.tmName, logoUrl:row.logoUrl}
      this.tmform = {...row}  // 等同于上面的代码，注意不用直接将row赋值给tmform
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.tmform.logoUrl = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 添加或者更新品牌的方法
    addOrUpdateTradeMark(formName){
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false
      
          const result = await this.$API.trademark.reqAddOrUpdateTradeMark(this.tmform)
          if(result.code == 200){
            this.$message({
              message: this.tmform.id?'修改品牌成功！':'添加品牌成功！',
              type: 'success'
            })
            // 如果是添加品牌，则停留在第一页；如果是修改品牌，则停留在当前页
            this.page = this.tmform.id?this.page:1
            this.getPageList()
          }else{
            this.$message.error(this.tmform.id?'修改品牌失败！':'添加品牌失败！')
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    deleteTradeMark(row){

      this.$confirm(`你确定删除${row.tmName}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let result = await this.$API.trademark.reqDeleteTradeMark(row.id)
        if(result.code == 200){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 再次获取品牌列表数据
          this.page = this.list.length>1?this.page:this.page-1
          this.page = this.page>=1?this.page:1
          this.getPageList()
        }
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }

  }

}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
